package com.chengyu.core.controller.common;

import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chengyu.core.controller.UserBaseController;
import com.chengyu.core.entity.CommonResult;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.model.SysDouyinConfig;
import com.chengyu.core.model.UmsMemberThirdAccount;
import com.chengyu.core.service.member.MemberThirdAccountService;
import com.chengyu.core.service.system.DouyinConfigService;
import com.chengyu.core.util.JsonUtil;
import com.chengyu.core.util.douyin.DouyinUtil;
import com.chengyu.core.util.netty.HttpClientUtil;
import com.chengyu.core.utils.HttpUtil;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author LeGreen
 * @title 公共管理类
 * @date 2021/1/8
 */
@Log4j2
@Api(tags = "公共管理类")
@Controller
@RequestMapping("/common")
public class DyController extends UserBaseController {
    @Autowired
    private MemberThirdAccountService memberThirdAccountService;
    @Autowired
    private DouyinConfigService douyinService;


    @RequestMapping("/dy/getIframeVideo")
    @ResponseBody
    public CommonResult<JSONObject> getIframeVideo(String videoId) throws Exception {
        Map<String, String> map = new HashMap();
        map.put("video_id", videoId);
        String result = HttpUtil.doGetMap(DouyinUtil.GET_IFRAME_BY_VIDEO, map);
        JSONObject resultJson = JSON.parseObject(result);
        System.out.println(resultJson);
        if (resultJson.getString("err_no").equals("28003004")){
            throw new ServiceException(resultJson.getString("err_msg"));
        }
        String iframe_code_old = resultJson.getJSONObject("data").getString("iframe_code");
        String iframe_code_New = iframe_code_old.replace("height=\"1280\"","height=\"750\"");
        System.out.println(iframe_code_New);
        Integer aaa= iframe_code_New.indexOf("src");
        Integer bbb= iframe_code_New.indexOf("referrerpolicy");
        String webViewSrc = iframe_code_New.substring(aaa+5, bbb-2);
        resultJson.getJSONObject("data").put("iframe_code",iframe_code_New);
        resultJson.getJSONObject("data").put("webViewSrc",webViewSrc);
        return CommonResult.success(resultJson);
    }


    @RequestMapping("/dy/getPublish")
    @ResponseBody
    public CommonResult<JSONObject> getPublish(String openId, String videoId) throws Exception {
        SysDouyinConfig config = douyinService.getDouyinConfig();
        String clientKey = config.getClientKey();
        Map<String, Object> map = new HashMap();
        String accessToken = DouyinUtil.getAccessToken(openId, clientKey);
        if (accessToken.equals("10020")) {
            throw new ServiceException("抖音账号授权到期，请重新授权");
        }

        List list = new ArrayList();
        list.add(videoId);
        map.put("video_ids", list);


        Map<String, Object> mapHeader = new HashMap();
        mapHeader.put("access-token", accessToken);
        mapHeader.put("content-type", "application/json");
        String result = HttpClientUtil.httpPostRequest(DouyinUtil.VIDEO_DATA + "?open_id=" + openId, mapHeader, map);
        JSONObject resultJson = JSON.parseObject(result);
        return CommonResult.success(resultJson);
    }

    @RequestMapping("/dy/selectPublish")
    @ResponseBody
    public CommonResult<JSONObject> selectPublish(String openId, String pageNum, String pageSize) throws Exception {
        SysDouyinConfig config = douyinService.getDouyinConfig();
        String clientKey = config.getClientKey();
        Map<String, String> map = new HashMap();
        String accessToken = DouyinUtil.getAccessToken(openId, clientKey);
        if (accessToken.equals("10020")) {
            throw new ServiceException("抖音账号授权到期，请重新授权");
        }
        map.put("count", pageSize);
        map.put("open_id", openId);
        map.put("cursor", pageNum);

        Map<String, String> mapHeader = new HashMap();
        mapHeader.put("access-token", accessToken);
        mapHeader.put("content-type", "application/json");
        String result = HttpUtil.doGetMap(DouyinUtil.VIDEO_LIST, map, mapHeader);
        JSONObject resultJson = JSON.parseObject(result);
        return CommonResult.success(resultJson);
    }


    @RequestMapping("/dy/publishTrends")
    @ResponseBody
    public CommonResult<String> publishTrends(String title, String shareToPublish, Integer type, String videoUrl, String imgUrl, String imgUrlList) throws Exception {
        SysDouyinConfig config = douyinService.getDouyinConfig();
        String clientKey = config.getClientKey();
        String clientSecret = config.getClientSecret();
        Map signatureMap = DouyinUtil.getSignature(clientKey, clientSecret);
        String client_key = signatureMap.get("clientKey").toString();
        String signature = signatureMap.get("signature").toString();
        String timestamp = signatureMap.get("timestamp").toString();
        String nonceStr = signatureMap.get("nonceStr").toString();
        URIBuilder uri = new URIBuilder("snssdk1128://openplatform/share");
        uri.addParameter("client_key", client_key);
//        uri.addParameter("state", share_id);
        uri.addParameter("nonce_str", nonceStr);
        uri.addParameter("timestamp", String.valueOf(timestamp));
        uri.addParameter("signature", signature);
        uri.addParameter("share_type", "h5");
        uri.addParameter("share_to_publish", shareToPublish);
        uri.addParameter("title", title);

        if (type == 1) {
            videoUrl = URLUtil.encode(videoUrl);
            uri.addParameter("video_path", videoUrl);
        } else if (type == 2) {
            imgUrl = URLUtil.encode(imgUrl);
            uri.addParameter("image_path", imgUrl);
        } else if (type == 3) {
            String[] imgUrlListArray = imgUrlList.split(",");
            JSONArray imgUrlListJsonArray = new JSONArray();
            for (String imgUrlItem : imgUrlListArray) {
                imgUrlItem = URLUtil.encode(imgUrlItem);
                imgUrlListJsonArray.put(imgUrlItem);
            }
            uri.addParameter("image_list_path", imgUrlListJsonArray.toString());
        }
        String url = uri.build().toString();
        return CommonResult.success(url);
    }


    @RequestMapping("/dy/getQrCode")
    @ResponseBody
    public CommonResult<JSONObject> getQrCode() throws Exception {
        SysDouyinConfig config = douyinService.getDouyinConfig();
        String clientKey = config.getClientKey();
        String redirectUrl = config.getRedirectUrl();
        String scope = config.getScope();

        Map<String, String> map = new HashMap();
        map.put("client_key", clientKey);
        map.put("scope", scope);
        map.put("next", redirectUrl);
        map.put("jump_type", "native");
        map.put("optional_scope_check", "");
        map.put("optional_scope_uncheck", "");
        map.put("customize_params", "{\"comment_id\":\"\",\"source\":\"pc_auth\",\"not_skip_confirm\":\"true\",\"enter_from\":\"\"}");
        String result = HttpUtil.doGetMap(DouyinUtil.QRCODE_URL, map);
        JSONObject resultJson = JSON.parseObject(result);
        return CommonResult.success(resultJson);
    }

    @RequestMapping("/dy/checkQrCode")
    @ResponseBody
    public CommonResult<JSONObject> checkQrCode(String token, Integer type) throws Exception {
        SysDouyinConfig config = douyinService.getDouyinConfig();
        String clientKey = config.getClientKey();
        String clientSecret = config.getClientSecret();
        String redirectUrl = config.getRedirectUrl();
        String scope = config.getScope();

        Map<String, String> map = new HashMap();
        map.put("client_key", clientKey);
        map.put("scope", scope);
        map.put("next", redirectUrl);
        map.put("token", token);
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("jump_type", "native");
        map.put("optional_scope_check", "");
        map.put("optional_scope_uncheck", "");
        map.put("customize_params", "{\"comment_id\":\"\",\"source\":\"pc_auth\",\"not_skip_confirm\":\"true\"}");
        String result = HttpUtil.doGetMap(DouyinUtil.CHECK_QRCODE_URL, map);
        JSONObject resultJson = JSON.parseObject(result);
        JSONObject dataJSON = resultJson.getJSONObject("data");
        if (dataJSON.getString("status").equals("confirmed")) {
            //如果确认授权了，就拿着code去获取用户信息（第一次根据code去授权，成功后保存到redis），
            //获取accesstoken
            String grant_type = "authorization_code";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", dataJSON.getString("code"));
            jsonObject.put("grant_type", grant_type);
            jsonObject.put("client_key", clientKey);
            jsonObject.put("client_secret", clientSecret);
            String data = jsonObject.toJSONString();
            String accessTokenDataStr = HttpClientUtil.httpPostRequest(DouyinUtil.ACCESS_TOKEN_URL, data);
            //同时将access_token和refresh_token保存到缓存
            JSONObject accessTokenJson = JSONObject.parseObject(accessTokenDataStr);
            JSONObject accessTokenData = accessTokenJson.getJSONObject("data");
            String access_token = accessTokenData.getString("access_token");
            String refresh_token = accessTokenData.getString("refresh_token");
            String open_id = accessTokenData.getString("open_id");
            Long expires_in = accessTokenData.getLong("expires_in");
            Long refresh_expires_in = accessTokenData.getLong("refresh_expires_in");
            redisUtil.delete(DouyinUtil.DY_ACCESS_TOKEN_KEY + "_" + open_id);
            redisUtil.delete(DouyinUtil.DY_REFRESH_TOKEN_KEY + "_" + open_id);
            redisUtil.setRedisValue(DouyinUtil.DY_ACCESS_TOKEN_KEY + "_" + open_id, access_token, expires_in, TimeUnit.SECONDS);
            redisUtil.setRedisValue(DouyinUtil.DY_REFRESH_TOKEN_KEY + "_" + open_id, refresh_token, refresh_expires_in, TimeUnit.SECONDS);
            //根据token获取用户信息
            JSONObject jsonObjectUser = new JSONObject();
            jsonObjectUser.put("access_token", access_token);
            jsonObjectUser.put("open_id", open_id);
            String dataUser = jsonObjectUser.toJSONString();
            String userInfo = HttpClientUtil.httpPostRequest(DouyinUtil.USERINFO_URL, dataUser);
            JSONObject userInfoJson = JSONObject.parseObject(userInfo);
            Gson gson = new Gson();
            userInfoJson.getJSONObject("data").remove("error_code");
            //驼峰转换
            Object caseResult = JsonUtil.convertUnderlineToCamelCase(userInfoJson.toJSONString());
            JSONObject userInfoJsonCase = (JSONObject) caseResult;
            UmsMemberThirdAccount umsMemberThirdAccount = gson.fromJson(userInfoJsonCase.getJSONObject("data").toString(), UmsMemberThirdAccount.class);
            //获取到用户后将他添加到会员和三方账号对应表
            umsMemberThirdAccount.setMemberId(getCurrentMemberId());
            umsMemberThirdAccount.setType(type);
            umsMemberThirdAccount.setAccessToken(access_token);
            umsMemberThirdAccount.setRefreshToken(refresh_token);
            umsMemberThirdAccount.setAddBy(getCurrentMember().getNickname());
            umsMemberThirdAccount.setAddTime(new Date());
            //先查看是否已经有这样的账号oauth/access_token
            List<UmsMemberThirdAccount> umsMemberThirdAccounts = memberThirdAccountService.checkIsExist(umsMemberThirdAccount);
            if (umsMemberThirdAccounts.size() == 0) {
                //如果不存在直接添加
                memberThirdAccountService.add(umsMemberThirdAccount);
            } else {
                //如果存在就先删除了再添加(重新认证)
                memberThirdAccountService.delete(umsMemberThirdAccounts.get(0).getId());
                memberThirdAccountService.add(umsMemberThirdAccount);
            }

        }
        return CommonResult.success(resultJson);
    }

    @RequestMapping("/dy/getUserInfoByCode")
    @ResponseBody
    public CommonResult<JSONObject> getUserInfoByCode(String code, Integer type) throws Exception {
        SysDouyinConfig config = douyinService.getDouyinConfig();
        String clientKey = config.getClientKey();
        String clientSecret = config.getClientSecret();

        String grant_type = "authorization_code";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("grant_type", grant_type);
        jsonObject.put("client_key", clientKey);
        jsonObject.put("client_secret", clientSecret);
        String data = jsonObject.toJSONString();
        String accessToken = HttpClientUtil.httpPostRequest(DouyinUtil.ACCESS_TOKEN_URL, data);
        //根据token获取用户信息
        JSONObject accessTokenJson = JSONObject.parseObject(accessToken);
        JSONObject accessTokenData = accessTokenJson.getJSONObject("data");
        String access_token = accessTokenData.getString("access_token");
        String refresh_token = accessTokenData.getString("refresh_token");
        String open_id = accessTokenData.getString("open_id");

        redisUtil.delete(DouyinUtil.DY_ACCESS_TOKEN_KEY + "_" + open_id);
        redisUtil.delete(DouyinUtil.DY_REFRESH_TOKEN_KEY + "_" + open_id);
        redisUtil.setRedisValue(DouyinUtil.DY_ACCESS_TOKEN_KEY + "_" + open_id, access_token, accessTokenData.getLong("expires_in"), TimeUnit.SECONDS);
        redisUtil.setRedisValue(DouyinUtil.DY_REFRESH_TOKEN_KEY + "_" + open_id, refresh_token, accessTokenData.getLong("refresh_expires_in"), TimeUnit.SECONDS);
        JSONObject jsonObjectUser = new JSONObject();
        jsonObjectUser.put("access_token", access_token);
        jsonObjectUser.put("open_id", open_id);
        String dataUser = jsonObjectUser.toJSONString();
        String userInfo = HttpClientUtil.httpPostRequest(DouyinUtil.USERINFO_URL, dataUser);
        JSONObject userInfoJson = JSONObject.parseObject(userInfo);
        Gson gson = new Gson();
        userInfoJson.getJSONObject("data").remove("error_code");
        //驼峰转换
        Object caseResult = JsonUtil.convertUnderlineToCamelCase(userInfoJson.toJSONString());
        JSONObject userInfoJsonCase = (JSONObject) caseResult;
        UmsMemberThirdAccount umsMemberThirdAccount = gson.fromJson(userInfoJsonCase.getJSONObject("data").toString(), UmsMemberThirdAccount.class);
        //获取到用户后将他添加到会员和三方账号对应表
        umsMemberThirdAccount.setMemberId(getCurrentMemberId());
        umsMemberThirdAccount.setType(type);
        umsMemberThirdAccount.setAccessToken(access_token);
        umsMemberThirdAccount.setRefreshToken(refresh_token);
        umsMemberThirdAccount.setAddBy(getCurrentMember().getNickname());
        umsMemberThirdAccount.setAddTime(new Date());
        //先查看是否已经有这样的账号oauth/access_token
        List<UmsMemberThirdAccount> umsMemberThirdAccounts = memberThirdAccountService.checkIsExist(umsMemberThirdAccount);
        if (umsMemberThirdAccounts.size() == 0) {
            //如果不存在直接添加
            memberThirdAccountService.add(umsMemberThirdAccount);
        } else {
            //如果存在就先删除了再添加(重新认证)
            memberThirdAccountService.delete(umsMemberThirdAccounts.get(0).getId());
            memberThirdAccountService.add(umsMemberThirdAccount);
        }
        return CommonResult.success(null);
    }

    public static void main(String[] args) {
//        String client_key = "aw6o7mdniw8qsxp8";
//        Map<String, String> map = new HashMap();
//        map.put("client_key", client_key);
//        map.put("response_type", "code");
//        map.put("scope", "user_info,trial.whitelist");
//        map.put("next", "https://backend.portal.lmvam.com/common/dy/getCodeForInfo");
//        map.put("jump_type", "native");
//        map.put("optional_scope_check", "");
//        map.put("optional_scope_uncheck", "");
//        map.put("customize_params", "{\"comment_id\":\"\",\"source\":\"pc_auth\",\"not_skip_confirm\":\"true\",\"enter_from\":\"\"}");
//        String result = HttpUtil.doGetMap("https://open.douyin.com/platform/oauth/connect/", map);
//        JSONObject resultJson = JSON.parseObject(result);
//        System.out.println(resultJson);
        String a = "<web-view width=\"720\" height=\"750\" frameborder=\"0\" src=\"https://open.douyin.com/player/video?vid=7345460186255084819&autoplay=0\" referrerpolicy=\"unsafe-url\" allowfullscreen></web-view>\n";
        Integer aaa= a.indexOf("src");
        Integer bbb= a.indexOf("referrerpolicy");
        String substring = a.substring(aaa+5, bbb-2);
        System.out.println(substring);
    }


}
